<template>
    <div class="app-container">
        <el-form v-show="showSearch" ref="queryRef" :model="queryParams" :inline="true" label-width="68px">
            <el-form-item label="客户姓名" prop="roleName">
                <el-input
                    v-model="queryParams.name"
                    placeholder="请输入客户姓名"
                    clearable
                    style="width: 240px"
                    @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item label="客户手机" prop="roleKey">
                <el-input
                    v-model="queryParams.phone"
                    placeholder="请输入客户手机号"
                    clearable
                    style="width: 240px"
                    @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item label="归属人" prop="status">
                <el-input
                    v-model="queryParams.owner"
                    placeholder="请输入商机归属人"
                    clearable
                    style="width: 240px"
                    @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item label="跟进时间" style="width: 500px">
                <el-date-picker
                    v-model="dateRange"
                    value-format="YYYY-MM-DD"
                    type="daterange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                ></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    v-hasPermi="['system:role:add']"
                    type="primary"
                    plain
                    icon="Plus"
                    @click="handleAdd"
                    >新增</el-button
                >
            </el-col>
            <el-col :span="1.5">
                <el-button
                    v-hasPermi="['system:role:edit']"
                    type="success"
                    plain
                    icon="Edit"
                    :disabled="single"
                    @click="handleUpdate"
                    >修改</el-button
                >
            </el-col>
            <el-col :span="1.5">
                <el-button
                    v-hasPermi="['system:role:remove']"
                    type="danger"
                    plain
                    icon="Delete"
                    :disabled="multiple"
                    @click="handleDelete"
                    >删除</el-button
                >
            </el-col>
            <el-col :span="1.5">
                <el-button
                    v-hasPermi="['system:role:export']"
                    type="warning"
                    plain
                    icon="Download"
                    @click="handleExport"
                    >导出</el-button
                >
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <!-- 表格数据 -->
        <el-table v-loading="loading" :data="roleList" @selectionChange="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="客户姓名" prop="name" width="120" />
            <el-table-column label="手机号" prop="phone" :show-overflow-tooltip="true" width="150" />
            <el-table-column label="商机归属" prop="owner" :show-overflow-tooltip="true" width="150" />
            <el-table-column label="创建时间" align="center" prop="createTime">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="商机状态" align="center" width="100">
                <template #default="scope">
                    <el-tag v-if="scope.row.status == '0'" >已分配</el-tag>
                    <el-tag v-if="scope.row.status == '1'" >进行中</el-tag>
                    <el-tag v-if="scope.row.status == '2'" >回收</el-tag>
                    <el-tag v-if="scope.row.status == '3'" type="danger">未知状态</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="下次跟进时间" align="center" prop="updateTime">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.nextTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-tooltip content="查看" placement="top">
                        <el-button
                            v-hasPermi="['system:role:edit']"
                            link
                            type="primary"
                            icon="View"
                            @click="handleView(scope.row)"
                            >查看</el-button
                        >
                    </el-tooltip>
                    <el-tooltip content="分配" placement="top" v-if="scope.row.status !== 3 && scope.row.status !== 2">
                        <el-button
                            v-hasPermi="['system:role:edit']"
                            link
                            type="primary"
                            icon="Pointer"
                            @click="handleDataScope(scope.row)"
                            >分配</el-button
                        > 
                    </el-tooltip>
                    <el-tooltip content="跟进" placement="top" v-if="scope.row.status !== 3 && scope.row.status !== 2">
                        <el-button
                            v-hasPermi="['system:role:edit']"
                            link
                            type="primary"
                            icon="Position"
                            @click="handleAuthUser(scope.row)"
                            >跟进</el-button
                        >
                    </el-tooltip>
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total > 0"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            :total="total"
            @pagination="getList"
        />

        <!-- 添加或修改角色配置对话框 -->
        <el-dialog v-model="open" :title="title" width="700px" append-to-body>
            <el-form ref="roleRef" :model="form" :rules="rules" label-width="100px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="手机号" prop="phone">
                            <el-input v-model="form.phone" placeholder="请输入手机号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="客户姓名" prop="name">
                            <el-input v-model="form.name" placeholder="请输入客户姓名" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="渠道来源" prop="channelId">
                            <el-select v-model="form.channelId" @change="getActivity">
                                <el-option
                                    v-for="channel in channelsList"
                                    :key="channel.channelId"
                                    :value="channel.channelId"
                                    :label="channel.channelName"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="活动信息" prop="activityId">
                            <el-select v-model="form.activityId">
                              <el-option
                                    v-for="activity in activityList"
                                    :key="activity.activityId"
                                    :value="activity.activityId"
                                    :label="activity.activityName"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="年龄" prop="age">
                            <el-input-number v-model="form.age" controls-position="right" :min="0" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="性别" prop="gender">
                            <el-radio-group v-model="form.gender">
                                <el-radio :label="0">男</el-radio>
                                <el-radio :label="1">女</el-radio>
                                <el-radio :label="2">未知</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="微信号" prop="weixin">
                            <el-input v-model="form.weixin" placeholder="请输入微信号"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="QQ号码" prop="qq">
                            <el-input v-model="form.qq" placeholder="请输入QQ号码"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="Role" lang="ts">
/* eslint-disable camelcase */
import { addRole, delRole, getRole, listRole, updateRole, channels ,activity } from '@/api/system/business';
import { parseTime } from '@/utils/ruoyi';
import { getCurrentInstance, ComponentInternalInstance, ref, reactive, toRefs } from 'vue';
import { useRouter } from 'vue-router';

const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const roleList = ref<any[]>([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<number[]>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref('');
const dateRange = ref<any>([]);
const menuExpand = ref(false);
const menuNodeAll = ref(false);
const deptExpand = ref(true);
const deptNodeAll = ref(false);
const openDataScope = ref(false);
const menuRef = ref<any>(null);
const channelsList = ref([]);
const activityList = ref([]);
const data = reactive<{
    form: any;
    queryParams: any;
    rules: any;
}>({
    form: {
        id: null, // 新增字段，用于标识当前记录的ID
        phone: '',
        name: '',
        channelId: "",
        activityId: '',
        gender: 0,
        weixin: '',
        qq: '',
        isEdit: false, // 新增字段，用于标识当前操作是新增还是修改
    },
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        roleName: undefined,
        roleKey: undefined,
        status: undefined,
    },
    rules: {
        phone: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
            { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
        ],
        name: [{ required: true, message: '请输入客户姓名', trigger: 'blur' }],
    },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询角色列表 */
function getList() {
    loading.value = true;
    listRole(proxy!.addDateRange(queryParams.value, dateRange.value)).then((response: any) => {
        roleList.value = response.rows;
        total.value = response.total;
        loading.value = false;
    });
}
/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}
/** 重置按钮操作 */
function resetQuery() {
    dateRange.value = [];
    proxy!.resetForm('queryRef');
    handleQuery();
}
/** 删除按钮操作 */
function handleDelete() {
    const businessIds = ids.value;
    proxy!.$modal
        .confirm('是否确认删除角色编号为"' + businessIds.join(', ') + '"的数据项?')
        .then(function () {
            return delRole(businessIds);
        })
        .then(() => {
            getList();
            proxy!.$modal.msgSuccess('删除成功');
        })
        .catch((e: any) => {
            console.log(e);
        });
}
/** 导出按钮操作 */
function handleExport() {
    proxy!.download(
        '/tienchin/channel/export',
        {
            ...queryParams.value,
        },
        `role_${new Date().getTime()}.xlsx`
    );
}
/** 多选框选中数据 */
function handleSelectionChange(selection: any[]) {
    ids.value = selection.map(item => item.businessId);
    single.value = selection.length !== 1;
    multiple.value = !selection.length;
}
/** 重置新增的表单以及其他数据  */
function reset() {
    if (menuRef.value) {
        menuRef.value.setCheckedKeys([]);
    }
    menuExpand.value = false;
    menuNodeAll.value = false;
    deptExpand.value = true;
    deptNodeAll.value = false;
    form.value = {
        id: null,
        phone: '',
        name: '',
        channelId: 1,
        activityId: 2,
        gender: 0,
        weixin: '',
        qq: '',
        isEdit: false,
    };
    proxy!.resetForm('roleRef');
}
/** 添加角色 */
function handleAdd() {
    reset();
    open.value = true;
    title.value = '添加角色';
    getActivity();
}

/** 修改按钮操作 */
function handleUpdate(row: any) {
    reset();
    const roleIds = ids.value;
    getRole(roleIds[0]).then((response: any) => {
        form.value = response.data;
        form.value.isEdit = true; // 确保这里设置了 isEdit 为 true
        open.value = true;
        title.value = '修改角色';
    });
    getActivity();
}

/** 提交按钮 */
function submitForm() {
    (proxy?.$refs['roleRef'] as any).validate((valid: any) => {
        if (valid) {
            if (form.value.isEdit) {
                // 修改角色
                updateRole(form.value).then(response => {
                    proxy!.$modal.msgSuccess('修改成功');
                    open.value = false;
                    getList();
                });
            } else {
                // 新增角色
                addRole(form.value).then(response => {
                    proxy!.$modal.msgSuccess('新增成功');
                    open.value = false;
                    getList();
                });
            }
        }
    });
}
// 商机查看
function handleView(row: any) {
    const businessId = row.businessId; // 假设 row 对象中有 businessId 属性
    router.push({ name: 'BusinessDetail', params: { id: businessId } });
}
function handleAuthUser(row: any){
    const businessId = row.businessId; // 假设 row 对象中有 businessId 属性
    router.push({ name: 'BusinessDetail', params: { id: businessId  }, query: { action: 'active' }   });
}
/** 取消按钮 */
function cancel() {
    open.value = false;
    reset();
}
// 获取所有商机渠道
function getChannels() {
    channels().then(res => {
        channelsList.value = res.data.map(item => ({
            channelName: item.channelName,
            channelId: item.channelId,
        }));
    });
}
// 根据渠道id获取对应促销活动列表
function getActivity() {
    activity(form.value.channelId).then(res => {
        activityList.value = res.data.map(item => ({
            activityName: item.name,
            activityId: item.activityId,
        }));
    });
}
getList();
getChannels()
</script>